<?php
/**
 * 图像处理类
 * 功能:
 * 	缩略图
 * 	缩放
 * 	裁剪
 * @copyright     Copyright 2012, Longui Software Foundation, Inc. (http://www.bicphp.org)
 * @link          http://bicphp.com Longui(tm) Project
 * @package       Bicphp.Image
 * @since         BicPHP(tm) v 1.0.0.2363
 * @license       GPL v3
 */
if (! defined ( 'IN_BIC' )) {
    die ( '非法图像处理访问来源!' );
}
class Bic_Image extends Bic_Base{

    //public
    public $url = null; //图片位置
    public $gd_info = array (); //gd库信息
    public $version = null; //gd库版本
    public $size = null; //图片大小
    public $type = null; //图片类型
    public $width = null; //图片宽
    public $height = null; //图片高
    public $bits = null; //图片位


    /**
     * 加载图片文件
     *
     * @param string $url	图片位置
     */
    function __construct($url) {
        //!defined('ROOT') && define("ROOT",substr(str_replace("\\","/",dirname(__FILE__)),0,-7));	//网站根目录
        ! is_file ( $url ) && $this->outMsg ( "[{$url}]该文件不存在!" ); //判断文件存在
        $imgInfo = getimagesize ( $url ); //获取图片信息
        $imgInfo ['mime'] == '' && $this->outMsg ( "[{$url}]该文件不是正常的图像文件!" ); //判断是否为图像文件


        /*图片数据*/
        $this->url = str_replace ( '\\', '/', $url ); //图片路径
        $this->size = $imgInfo [0]; //图片大小
        $this->type = strtolower ( substr ( $imgInfo ['mime'], 6, strlen ( $imgInfo ['mime'] ) ) ); //图片类型
        $this->width = $imgInfo [0]; //宽
        $this->height = $imgInfo [1]; //高
        $this->bits = $imgInfo ['bits']; //高


        /*gd库信息*/
        $this->gd_info = gd_info (); //gd库信息
        $this->version = $this->gd_info ['GD Version']; //gd库版本


    }

    /**
     * 图像大小调整
     * 	设定最大高和宽,按比例缩略出不超出此范围的最大 图像
     *
     * @param number $maxW	最大宽
     * @param number $maxH	最大高
     * @param string $newImg	是否将调整大小 后的图像以新文件重新生成,留空则表示修改原文件
     * @param string $operate	当新生成图像时,文件已存在 的处理方式 (1)alert:停止,并提示[默认] (2)del:删除已存在文件,不提示
     */
    function resize($maxW, $maxH,$newImg='',$operate='alert') {
        /*图像类型*/
        switch ($this->type) {
            case 'png' :
                $im = @ imagecreatefrompng ( $this->url );
                break;
            case 'jpeg' :
                $im = @ imagecreatefromjpeg($this->url);
                break;
            case 'gif' :
                $im = @ imagecreatefromgif($this->url);
                break;
            case 'bmp' :
                /*
                 * php没有自带的bmp图像创建函数！
                 * 要用其他函数。下面这个函数是在手册上找到的
                 */
                $im = @ $this->ImageCreateFromBMP($this->url);
                break;
        }

        /*新图像大小*/
        $ratio_x = $maxW/$this->width;	//宽 比
        $ratio_y = $maxH/$this->height;	//高 比
        if ( ($this->width <= $maxH) && ($this->height <= $maxW)){
            $newW = $this->width;
            $newH = $this->height;
        }else if (($ratio_y*$this->width) <=$maxW){
            $newW = ceil($this->width*$ratio_y);
            $newH = $maxH;
        }else {
            $newW = $maxW;
            $newH = ceil($this->height*$ratio_x);
        }

        /*图片处理*/
        if ($im) {
            /*$newImg不为空,则将缩略图以新文件$newImg生成*/
            if ($newImg!=''){
                /*图片已存在处理方式*/
                if (is_file($newImg)){
                    switch ($operate){
                        //停止并提示
                        case 'alert':
                        default:
                            $this->outMsg("图像调整大小提示您:<br />您要生成的缩略图[{$newImg}]已存在!您可以选择删除操作:del");
                            break;
                            //直接删除,不提示
                        case 'del':
                            if(! @unlink($newImg))
                            $this->outMsg("图像调整大小提示您:<br />[{$newImg}]文件删除失败,可能是您的权限不足!");
                            break;
                    }
                }
                //判断目录是否存在
                if(!is_dir(dirname($newImg))){
                    $this->outMsg("图像调整大小失败:<br />该目录[".dirname($newImg)."]不存在!");
                }
            }
            	
            	
            /*图像生成*/
            $dst_image = @imagecreatetruecolor($newW,$newH);
            imagealphablending($dst_image,false);    //gif透明用
            imagesavealpha($dst_image,true);    //gif透明用
            if(! imagecopyresampled($dst_image,$im,0,0,0,0,$newW,$newH,$this->width,$this->height))
            $this->outMsg("图像拷贝失败!");
            $fun = "image{$this->type}";	//生成图像函数
            $fun($dst_image,$newImg!=''?$newImg:$this->url);	//调用生成图像函数
            imagedestroy($im);
            imagedestroy($dst_image);
            chmod($newImg!=''?$newImg:$this->url,0755);
            	
        } else {
            $this->outMsg ( "{$this->type}图像创建失败,可能是您当前的GD库版本[{$this->version}],对此格式并不支持!" );
        }
        return true;
    }

    function thumb($maxW,$maxH,$newImg='',$operate='del'){
        if (trim($newImg)==''){
            $tmp=explode('.',$this->url);
            $end=$tmp[count($tmp)-1];
            $newImg=str_replace(".{$end}",'',$this->url).'_thumb.'.$end;
        }
        $this->resize($maxW,$maxH,$newImg,$operate);
        return $newImg;
    }

    /*********************************************/
    /* Fonction: ImageCreateFromBMP              */
    /* Author:   DHKold                          */
    /* Contact:  admin@dhkold.com                */
    /* Date:     The 15th of June 2005           */
    /* Version:  2.0B                            */
    /*********************************************/

    public function ImageCreateFromBMP($filename)
    {
        //Ouverture du fichier en mode binaire
        if (! $f1 = fopen($filename,"rb")) return FALSE;

        //1 : Chargement des ent�tes FICHIER
        $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
        if ($FILE['file_type'] != 19778) return FALSE;

        //2 : Chargement des ent�tes BMP
        $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                     '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                     '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
        $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
        if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
        $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
        $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
        $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
        $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
        $BMP['decal'] = 4-(4*$BMP['decal']);
        if ($BMP['decal'] == 4) $BMP['decal'] = 0;

        //3 : Chargement des couleurs de la palette
        $PALETTE = array();
        if ($BMP['colors'] < 16777216)
        {
            $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
        }

        //4 : Cr�ation de l'image
        $IMG = fread($f1,$BMP['size_bitmap']);
        $VIDE = chr(0);

        $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
        $P = 0;
        $Y = $BMP['height']-1;
        while ($Y >= 0)
        {
            $X=0;
            while ($X < $BMP['width'])
            {
                if ($BMP['bits_per_pixel'] == 24)
                $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
                elseif ($BMP['bits_per_pixel'] == 16)
                {
                    $COLOR = unpack("n",substr($IMG,$P,2));
                    $COLOR[1] = $PALETTE[$COLOR[1]+1];
                }
                elseif ($BMP['bits_per_pixel'] == 8)
                {
                    $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
                    $COLOR[1] = $PALETTE[$COLOR[1]+1];
                }
                elseif ($BMP['bits_per_pixel'] == 4)
                {
                    $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
                    if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
                    $COLOR[1] = $PALETTE[$COLOR[1]+1];
                }
                elseif ($BMP['bits_per_pixel'] == 1)
                {
                    $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
                    if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
                    elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
                    elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
                    elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
                    elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
                    elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
                    elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
                    elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
                    $COLOR[1] = $PALETTE[$COLOR[1]+1];
                }
                else
                return FALSE;
                imagesetpixel($res,$X,$Y,$COLOR[1]);
                $X++;
                $P += $BMP['bytes_per_pixel'];
            }
            $Y--;
            $P+=$BMP['decal'];
        }

        //Fermeture du fichier
        fclose($f1);

        return $res;
    }

    /**
     *
     */
    function __destruct() {

    }
}

?>
